package com.easysettle

import android.content.Intent
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Typeface
import android.os.Bundle
import android.os.ParcelFileDescriptor
import android.print.PageRange
import android.print.PrintAttributes
import android.print.PrintDocumentAdapter
import android.print.PrintDocumentInfo
import android.print.PrintManager
import android.util.Log
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import android.widget.Button
import android.widget.ImageButton
import android.widget.LinearLayout
import android.widget.ScrollView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.easysettle.model.CartItem
import com.easysettle.service.MainService
import java.io.FileOutputStream
import java.io.OutputStream
import java.text.DecimalFormat
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale

/**
 * 收据Activity
 * 用于显示购物结算后的收据信息
 */
class ReceiptActivity : AppCompatActivity() {
    // 常量定义
    private val TAG = "ReceiptActivity"
    
    // UI组件
    private lateinit var recyclerViewItems: RecyclerView
    private lateinit var tvReceiptNumber: TextView
    private lateinit var tvReceiptTime: TextView
    private lateinit var tvTotalAmount: TextView
    private lateinit var tvTotalItems: TextView
    private lateinit var btnPrint: Button
    private lateinit var btnComplete: Button
    private lateinit var btnBack: ImageButton
    private lateinit var tvEmptyReceipt: TextView
    private lateinit var scrollViewContent: ScrollView
    
    // 添加对主内容区域的引用
    private lateinit var receiptHeaderLayout: LinearLayout
    private lateinit var itemsHeaderLayout: LinearLayout
    private lateinit var summaryLayout: LinearLayout
    private lateinit var footerInfoLayout: LinearLayout
    private lateinit var buttonsLayout: LinearLayout
    
    // 购物车商品列表
    private lateinit var cartItems: List<CartItem>
    // 商品适配器
    private lateinit var receiptAdapter: ReceiptAdapter
    // 收据号
    private lateinit var receiptNumber: String
    // 收据时间
    private lateinit var receiptTime: String
    // 总金额
    private var totalAmount: Double = 0.0
    // 主服务实例
    private lateinit var mainService: MainService
    // 格式化工具
    private val decimalFormat = DecimalFormat("0.00")
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_receipt)
        
        Log.d(TAG, "ReceiptActivity onCreate开始")
        
        // 初始化UI组件
        recyclerViewItems = findViewById(R.id.recycler_view_items)
        tvReceiptNumber = findViewById(R.id.tv_receipt_number)
        tvReceiptTime = findViewById(R.id.tv_receipt_time)
        tvTotalAmount = findViewById(R.id.tv_total_amount)
        tvTotalItems = findViewById(R.id.tv_total_items)
        btnPrint = findViewById(R.id.btn_print)
        btnComplete = findViewById(R.id.btn_complete)
        btnBack = findViewById(R.id.btn_back)
        tvEmptyReceipt = findViewById(R.id.tv_empty_receipt)
        scrollViewContent = findViewById(R.id.scroll_view_content)
        
        // 初始化布局引用
        receiptHeaderLayout = findViewById(R.id.receipt_header_layout)
        itemsHeaderLayout = findViewById(R.id.items_header_layout)
        summaryLayout = findViewById(R.id.summary_layout)
        footerInfoLayout = findViewById(R.id.footer_info_layout)
        buttonsLayout = findViewById(R.id.buttons_layout)
        
        // 确保所有UI元素默认可见
        recyclerViewItems.visibility = View.VISIBLE
        tvReceiptNumber.visibility = View.VISIBLE
        tvReceiptTime.visibility = View.VISIBLE
        tvTotalAmount.visibility = View.VISIBLE
        tvTotalItems.visibility = View.VISIBLE
        btnPrint.visibility = View.VISIBLE
        btnComplete.visibility = View.VISIBLE
        btnBack.visibility = View.VISIBLE
        tvEmptyReceipt.visibility = View.GONE
        scrollViewContent.visibility = View.VISIBLE
        
        // 确保所有布局可见
        receiptHeaderLayout.visibility = View.VISIBLE
        itemsHeaderLayout.visibility = View.VISIBLE
        summaryLayout.visibility = View.VISIBLE
        footerInfoLayout.visibility = View.VISIBLE
        buttonsLayout.visibility = View.VISIBLE
        
        // 初始化主服务
        mainService = MainService(this)
        
        // 从Intent中获取数据
        intent?.let { intent ->
            // 初始化数据变量
            receiptNumber = intent.getStringExtra("receiptNumber") ?: ""
            receiptTime = intent.getStringExtra("receiptTime") ?: ""
            totalAmount = intent.getDoubleExtra("totalAmount", 0.0)
            
            // 安全地获取购物车数据
            try {
                val serializableData = intent.getSerializableExtra("cartItems")
                if (serializableData is List<*>) {
                    // 过滤并转换为CartItem列表
                    cartItems = serializableData.filterIsInstance<CartItem>()
                    Log.d(TAG, "成功转换购物车数据，有效商品数量: ${cartItems.size}")
                } else {
                    cartItems = emptyList()
                    Log.w(TAG, "购物车数据类型不匹配，设置为空列表")
                }
            } catch (e: Exception) {
                cartItems = emptyList()
                Log.e(TAG, "获取购物车数据失败: ${e.message}", e)
            }
            
            // 调试日志
            Log.d(TAG, "从Intent接收数据:")
            Log.d(TAG, "receiptNumber: $receiptNumber")
            Log.d(TAG, "receiptTime: $receiptTime")
            Log.d(TAG, "totalAmount: $totalAmount")
            Log.d(TAG, "cartItems大小: ${cartItems.size}")
            if (cartItems.isNotEmpty()) {
                Log.d(TAG, "第一个商品: ${cartItems[0].product.name}, 价格: ${cartItems[0].product.price}, 数量: ${cartItems[0].quantity}")
            }
        }
        
        // 处理没有数据的情况
        if (cartItems.isEmpty() && totalAmount == 0.0 && receiptNumber.isEmpty()) {
            // 直接从MainActivity进入，没有结算数据
            Log.d(TAG, "没有接收到结算数据，显示空收据界面")
            btnPrint.visibility = View.GONE
            btnComplete.visibility = View.GONE
            recyclerViewItems.visibility = View.GONE
            receiptHeaderLayout.visibility = View.GONE
            itemsHeaderLayout.visibility = View.GONE
            summaryLayout.visibility = View.GONE
            footerInfoLayout.visibility = View.GONE
            buttonsLayout.visibility = View.GONE
            tvEmptyReceipt.visibility = View.VISIBLE
        } else {
            Log.d(TAG, "成功接收到结算数据，准备显示收据")
            // 确保所有收据相关UI元素可见
            tvEmptyReceipt.visibility = View.GONE
            recyclerViewItems.visibility = View.VISIBLE
            receiptHeaderLayout.visibility = View.VISIBLE
            itemsHeaderLayout.visibility = View.VISIBLE
            summaryLayout.visibility = View.VISIBLE
            footerInfoLayout.visibility = View.VISIBLE
            btnPrint.visibility = View.VISIBLE
            btnComplete.visibility = View.VISIBLE
            buttonsLayout.visibility = View.VISIBLE
        }
        
        // 设置返回按钮点击事件
        btnBack.setOnClickListener {
            setResult(RESULT_CANCELED)
            finish()
        }
        
        // 设置完成按钮点击事件
        btnComplete.setOnClickListener {
            setResult(RESULT_OK)
            finish()
        }
        
        // 初始化RecyclerView
        try {
            recyclerViewItems.layoutManager = LinearLayoutManager(this)
            Log.d(TAG, "RecyclerView布局管理器设置完成")
            
            receiptAdapter = ReceiptAdapter(cartItems)
            Log.d(TAG, "ReceiptAdapter创建完成，商品数量: ${cartItems.size}")
            
            recyclerViewItems.adapter = receiptAdapter
            Log.d(TAG, "RecyclerView适配器设置完成")
            Log.d(TAG, "RecyclerView初始化完成")
        } catch (e: Exception) {
            Log.e(TAG, "RecyclerView初始化失败: ${e.message}", e)
            Toast.makeText(this, "收据列表初始化失败", Toast.LENGTH_SHORT).show()
        }
        
        // 显示收据信息
        try {
            displayReceiptInfo()
            Log.d(TAG, "收据信息显示完成")
        } catch (e: Exception) {
            Log.e(TAG, "显示收据信息失败: ${e.message}", e)
            Toast.makeText(this, "显示收据信息失败", Toast.LENGTH_SHORT).show()
        }
        
        // 强制刷新UI
        runOnUiThread {
            Log.d(TAG, "强制刷新UI")
            recyclerViewItems.invalidate()
            recyclerViewItems.requestLayout()
            receiptAdapter.notifyDataSetChanged()
            
            // 刷新ScrollView
            scrollViewContent.invalidate()
            scrollViewContent.requestLayout()
            
            // 再次设置UI元素可见性，确保生效
            if (cartItems.isEmpty() && totalAmount == 0.0 && receiptNumber.isEmpty()) {
                btnPrint.visibility = View.GONE
                btnComplete.visibility = View.GONE
                recyclerViewItems.visibility = View.GONE
                receiptHeaderLayout.visibility = View.GONE
                itemsHeaderLayout.visibility = View.GONE
                summaryLayout.visibility = View.GONE
                footerInfoLayout.visibility = View.GONE
                buttonsLayout.visibility = View.GONE
                scrollViewContent.visibility = View.GONE
                tvEmptyReceipt.visibility = View.VISIBLE
            } else {
                tvEmptyReceipt.visibility = View.GONE
                recyclerViewItems.visibility = View.VISIBLE
                receiptHeaderLayout.visibility = View.VISIBLE
                itemsHeaderLayout.visibility = View.VISIBLE
                summaryLayout.visibility = View.VISIBLE
                footerInfoLayout.visibility = View.VISIBLE
                btnPrint.visibility = View.VISIBLE
                btnComplete.visibility = View.VISIBLE
                buttonsLayout.visibility = View.VISIBLE
                scrollViewContent.visibility = View.VISIBLE
            }
        }
        
        // 设置打印按钮点击事件
        btnPrint.setOnClickListener {
            printReceipt()
        }
        
        Log.d(TAG, "ReceiptActivity onCreate完成")
    }
    
    override fun onResume() {
        super.onResume()
        Log.d(TAG, "ReceiptActivity onResume - 再次刷新UI")
        
        // 在onResume生命周期再次刷新UI，确保视图完全渲染
        runOnUiThread {
            // 再次确保所有UI元素可见
            if (cartItems.isNotEmpty() || totalAmount > 0.0 || receiptNumber.isNotEmpty()) {
                recyclerViewItems.visibility = View.VISIBLE
                receiptHeaderLayout.visibility = View.VISIBLE
                itemsHeaderLayout.visibility = View.VISIBLE
                summaryLayout.visibility = View.VISIBLE
                footerInfoLayout.visibility = View.VISIBLE
                btnPrint.visibility = View.VISIBLE
                btnComplete.visibility = View.VISIBLE
                buttonsLayout.visibility = View.VISIBLE
                scrollViewContent.visibility = View.VISIBLE
                tvEmptyReceipt.visibility = View.GONE
                
                // 再次显示收据信息
                displayReceiptInfo()
                
                // 再次刷新RecyclerView
                receiptAdapter.notifyDataSetChanged()
                recyclerViewItems.requestLayout()
                recyclerViewItems.invalidate()
                
                // 再次刷新ScrollView
                scrollViewContent.requestLayout()
                scrollViewContent.invalidate()
                
                Log.d(TAG, "onResume - UI元素已再次设置为可见")
            }
        }
    }
    
    /**
     * 显示收据信息
     */
    private fun displayReceiptInfo() {
        // 显示收据号
        tvReceiptNumber.text = "收据号: $receiptNumber"
        Log.d(TAG, "设置收据号: $receiptNumber")
        tvReceiptNumber.visibility = View.VISIBLE
        
        // 显示收据时间
        tvReceiptTime.text = "时间: $receiptTime"
        Log.d(TAG, "设置收据时间: $receiptTime")
        tvReceiptTime.visibility = View.VISIBLE
        
        // 显示总金额
        val formattedAmount = "总计金额: ¥${decimalFormat.format(totalAmount)}"
        tvTotalAmount.text = formattedAmount
        Log.d(TAG, "设置总金额: $formattedAmount")
        tvTotalAmount.visibility = View.VISIBLE
        
        // 显示商品总数
        val formattedItems = "商品总数: ${cartItems.size}"
        tvTotalItems.text = formattedItems
        Log.d(TAG, "设置商品总数: $formattedItems")
        tvTotalItems.visibility = View.VISIBLE
    }
    
    /**
     * 打印收据
     */
    private fun printReceipt() {
        // 获取打印管理器
        val printManager = getSystemService(PRINT_SERVICE) as PrintManager
        
        // 创建打印适配器
        val printAdapter = createPrintDocumentAdapter()
        
        // 开始打印
        printManager.print(
            "收据_$receiptNumber",
            printAdapter,
            PrintAttributes.Builder().build()
        )
    }
    
    /**
     * 创建打印文档适配器
     */
    private fun createPrintDocumentAdapter(): PrintDocumentAdapter {
        return object : PrintDocumentAdapter() {
            override fun onLayout(
                oldAttributes: PrintAttributes?,
                newAttributes: PrintAttributes?,
                cancellationSignal: android.os.CancellationSignal?,
                callback: LayoutResultCallback?,
                extras: Bundle?
            ) {
                // 创建打印文档信息
                val info = PrintDocumentInfo.Builder("receipt_$receiptNumber.pdf")
                    .setContentType(PrintDocumentInfo.CONTENT_TYPE_DOCUMENT)
                    .setPageCount(1)
                    .build()
                 
                callback?.onLayoutFinished(info, true)
            }
             
            override fun onWrite(
                pages: Array<out PageRange>?,
                destination: ParcelFileDescriptor?,
                cancellationSignal: android.os.CancellationSignal?,
                callback: WriteResultCallback?
            ) {
                // 生成收据内容
                generateReceiptContent(destination!!.fileDescriptor)
                 
                callback?.onWriteFinished(arrayOf(PageRange.ALL_PAGES))
            }
        }
    }
    
    /**
     * 生成收据内容
     */
    private fun generateReceiptContent(fileDescriptor: java.io.FileDescriptor) {
        try {
            // 创建输出流
            val outputStream: OutputStream = FileOutputStream(fileDescriptor)
             
            // 生成收据内容
            val receiptContent = if (cartItems.isNotEmpty()) {
                // 使用购物车数据生成收据
                val sb = StringBuilder()
                sb.appendLine("小超市购物清单")
                sb.appendLine("--------------------")
                sb.appendLine("收据号: $receiptNumber")
                sb.appendLine("日期: $receiptTime")
                sb.appendLine("--------------------")
                sb.appendLine("商品名称    单价    数量    小计")
                sb.appendLine("--------------------")
                 
                cartItems.forEach {
                    val productName = it.product.name
                    val price = decimalFormat.format(it.product.price)
                    val quantity = it.quantity
                    val subtotal = decimalFormat.format(it.getSubtotal())
                    sb.appendLine(String.format("%-12s %-8s %-8d %-8s", productName, price, quantity, subtotal))
                }
                 
                sb.appendLine("--------------------")
                sb.appendLine("商品总数: ${cartItems.size}")
                sb.appendLine("总计金额: ¥${decimalFormat.format(totalAmount)}")
                sb.appendLine("--------------------")
                sb.appendLine("感谢您的光临！")
                sb.toString()
            } else {
                // 如果没有购物车数据，使用主服务生成的收据内容
                mainService.generateReceiptContent()
            }
             
            // 写入内容
            outputStream.write(receiptContent.toByteArray())
            outputStream.close()
             
            // 显示打印成功提示
            runOnUiThread {
                Toast.makeText(this, "收据已发送到打印服务", Toast.LENGTH_SHORT).show()
            }
        } catch (e: Exception) {
            Log.e(TAG, "生成收据内容失败", e)
            runOnUiThread {
                Toast.makeText(this, "生成收据内容失败", Toast.LENGTH_SHORT).show()
            }
        }
    }
    
    /**
     * 收据商品适配器类
     */
    inner class ReceiptAdapter(
        private val cartItems: List<CartItem>
    ) : androidx.recyclerview.widget.RecyclerView.Adapter<ReceiptAdapter.ReceiptItemViewHolder>() {
        
        inner class ReceiptItemViewHolder(itemView: View) : androidx.recyclerview.widget.RecyclerView.ViewHolder(itemView) {
            val tvItemName: TextView = itemView.findViewById(R.id.tv_item_name)
            val tvItemPrice: TextView = itemView.findViewById(R.id.tv_item_price)
            val tvItemQuantity: TextView = itemView.findViewById(R.id.tv_item_quantity)
            val tvItemSubtotal: TextView = itemView.findViewById(R.id.tv_item_subtotal)
        }
        
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ReceiptItemViewHolder {
            val view = layoutInflater.inflate(R.layout.item_receipt, parent, false)
            Log.d(TAG, "创建ViewHolder")
            return ReceiptItemViewHolder(view)
        }

        override fun onBindViewHolder(holder: ReceiptItemViewHolder, position: Int) {
            val cartItem = cartItems[position]
            val product = cartItem.product
            
            Log.d(TAG, "绑定ViewHolder位置: $position, 商品: ${product.name}, 价格: ${product.price}, 数量: ${cartItem.quantity}")
            
            // 显示商品信息
            holder.tvItemName.text = product.name
            holder.tvItemName.visibility = View.VISIBLE
            
            val priceText = decimalFormat.format(product.price)
            holder.tvItemPrice.text = priceText
            holder.tvItemPrice.visibility = View.VISIBLE
            
            holder.tvItemQuantity.text = cartItem.quantity.toString()
            holder.tvItemQuantity.visibility = View.VISIBLE
            
            val subtotalText = decimalFormat.format(cartItem.getSubtotal())
            holder.tvItemSubtotal.text = subtotalText
            holder.tvItemSubtotal.visibility = View.VISIBLE
        }
        
        override fun getItemCount(): Int {
            val count = cartItems.size
            Log.d(TAG, "RecyclerView item count: $count")
            return count
        }
    }
}